from google.appengine.api import users
from google.appengine.ext import webapp

from base import GetDateStr
from base_page import BaseHandler
from data import Request
from data import DonorProfile
from data import ManufacturerProfile

class HomePageHandler(BaseHandler):
 
  def GetRequestsByState(self, state):
    limit = 10
    q = Request().all().filter('state =', state)
    ret = q.order('-creation_date').fetch(limit + 1)
    reqs = []
    for r in ret:
      r.creation_date_str = GetDateStr(r.creation_date)
      reqs.append(r)
    if len(reqs) > limit:
      return (True, reqs[0:limit])
    else:
      return (False, reqs)
 

  def ProcessGet(self):
    self.Setup('home_page.html', show_search_box=True)
    
    has_more, pending = self.GetRequestsByState(Request.PENDING)
    has_more, open = self.GetRequestsByState(Request.OPEN)
    has_more, funded = self.GetRequestsByState(Request.FUNDED)
    has_more, ship = self.GetRequestsByState(Request.SHIP)
    has_more, closed = self.GetRequestsByState(Request.CLOSED)

    self.template_values['pending_reqs'] = pending
    self.template_values['open_reqs'] = open
    self.template_values['funded_reqs'] = funded
    self.template_values['ship_reqs'] = ship
    self.template_values['closed_reqs'] = closed

    # Get donors and manufactureres
    q = DonorProfile().all()
    donors = q.filter('state =', DonorProfile.ACTIVE).fetch(10)
    q = ManufacturerProfile().all()
    manufacturers = q.filter('state =', ManufacturerProfile.ACTIVE).fetch(10)
    self.template_values['donors'] = donors
    self.template_values['manufacturers'] = manufacturers
    self.Render()

